<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试案例管理</title>
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/static/css/bootstrap-icons.css">
    <style>
        body {
            background-color: #f0f7ff;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding-top: 20px;
        }
        .navbar {
            background-color: #0d6efd;
            margin-bottom: 30px;
        }
        .card {
            border: none;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .card-header {
            background-color: #0d6efd;
            color: white;
            font-weight: bold;
        }
        .search-bar {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .table-responsive {
            overflow-x: auto;
        }
        .table th {
            background-color: #e7f1ff;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        .pagination {
            justify-content: center;
            margin-top: 20px;
        }
        .system-suggestions {
            position: absolute;
            z-index: 100;
            width: calc(100% - 1.5rem);
            max-height: 200px;
            overflow-y: auto;
            background-color: white;
            border: 1px solid #ced4da;
            border-radius: 0.25rem;
            display: none;
        }
        .system-suggestion-item {
            padding: 8px 12px;
            cursor: pointer;
        }
        .system-suggestion-item:hover {
            background-color: #e7f1ff;
        }
        .alert-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1050;
            max-width: 350px;
        }
        .alert {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            animation: slideIn 0.3s ease-out;
        }
        .alert-success {
            background-color: #d1e7dd;
            color: #0f5132;
            border: 1px solid #badbcc;
        }
        .alert-danger {
            background-color: #f8d7da;
            color: #842029;
            border: 1px solid #f5c2c7;
        }
        .alert i {
            margin-right: 10px;
            font-size: 1.2em;
        }
        .alert .close-btn {
            margin-left: auto;
            background: none;
            border: none;
            font-size: 1.2em;
            cursor: pointer;
            color: inherit;
        }
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

<!--        .copy-tooltip {-->
<!--            position: relative;-->
<!--            display: inline-block;-->
<!--        }-->
<!--        .copy-tooltip .tooltip-text {-->
<!--            visibility: hidden;-->
<!--            width: 120px;-->
<!--            background-color: #333;-->
<!--            color: #fff;-->
<!--            text-align: center;-->
<!--            border-radius: 6px;-->
<!--            padding: 5px;-->
<!--            position: absolute;-->
<!--            z-index: 1;-->
<!--            bottom: 125%;-->
<!--            left: 50%;-->
<!--            margin-left: -60px;-->
<!--            opacity: 0;-->
<!--            transition: opacity 0.3s;-->
<!--            font-size: 0.8rem;-->
<!--        }-->
<!--        .copy-tooltip:hover .tooltip-text {-->
<!--            visibility: visible;-->
<!--            opacity: 1;-->
<!--        }-->



    </style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark">
    <div class="container">
        <a class="navbar-brand" href="/">
            <i class="bi bi-database-fill-gear me-2"></i>测试用例管理
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ms-auto">
                <li class="nav-item">
                    <a class="nav-link active" href="/">
                        <i class="bi bi-house-door me-1"></i>首页
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/add">
                        <i class="bi bi-plus-circle me-1"></i>添加信息
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/import">
                        <i class="bi bi-file-earmark-excel me-1"></i>导入Excel
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="exportLink" href="#">
                        <i class="bi bi-download me-1"></i>导出Excel
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#" data-bs-toggle="modal" data-bs-target="#fieldDescriptionModal">
                        <i class="bi bi-info-circle me-1"></i>字段说明
                    </a>
                </li>
            </ul>
        </div>
    </div>
</nav>
<div class="container">
    <div class="card">
        <div class="card-header">
            <h4><i class="bi bi-table me-2"></i>用例列表</h4>
        </div>
        <div class="card-body">
            <!-- 搜索区域 -->
            <div class="search-bar">
                <form method="get" action="/" class="row g-3">
                    <div class="col-md-3 position-relative">
                        <label for="system_name" class="form-label">系统名称</label>
                        <input type="text" class="form-control" id="system_name" name="system_name"
                               placeholder="请输入系统名称" value="{{ search_system }}">
                        <!-- 系统名称建议 -->
                        <div class="system-suggestions" id="systemSuggestions">
                            {% for system in system_list %}
                            <div class="system-suggestion-item" onclick="selectSystem('{{ system }}')">{{ system }}</div>
                            {% endfor %}
                        </div>
                    </div>
                    <!-- 新增版本号筛选条件 -->
                    <div class="col-md-3">
                        <label for="version" class="form-label">版本号</label>
                        <input type="text" class="form-control" id="version" name="version"
                               placeholder="请输入版本号" value="{{ search_version }}">
                    </div>
                    <div class="col-md-3">
                        <label for="case_id" class="form-label">用例编号</label>
                        <input type="text" class="form-control" id="case_id" name="case_id"
                               placeholder="请输入用例编号" value="{{ search_case_id }}">
                    </div>
                    <div class="col-md-3">
                        <label for="module" class="form-label">模块</label>
                        <input type="text" class="form-control" id="module" name="module"
                               placeholder="请输入模块名称" value="{{ search_module }}">
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="bi bi-search me-1"></i>搜索
                        </button>
                        <a href="/" class="btn btn-secondary">
                            <i class="bi bi-arrow-clockwise me-1"></i>重置
                        </a>
                    </div>
                </form>
            </div>

            <!-- 数据表格 - 显示操作序列 -->
            <div class="table-responsive">
                <table class="table table-hover table-striped">
                    <thead>
                    <tr>
                        <th>系统名称</th>
                        <th>版本号</th>  <!-- 新增版本号列 -->
                        <th>用例编号</th>
                        <th>操作序列</th>
                        <th>模块</th>
                        <th>标题</th>
                        <th>是否自动化</th>
                        <th>自动化状态</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    {% if gateway_info_list %}
                    {% for info in gateway_info_list %}
                    <tr data-id="{{ info.id }}">
                        <td>{{ info.system_name }}</td>
                        <td>{{ info.version }}</td>  <!-- 显示版本号 -->
                        <td>{{ info.case_id }}</td>
                        <td>{{ info.operation_sequence }}</td>
                        <td>{{ info.module }}</td>
                        <td>{{ info.title|truncate(30) }}</td>
                        <td>{{ info.is_automated }}</td>
                        <td>{{ info.automation_status }}</td>
                        <td class="action-buttons">
                            <a href="/view/{{ info.id }}" class="btn btn-sm btn-info" title="查看">
                                <i class="bi bi-eye"></i>
                            </a>
                            <a href="/edit/{{ info.id }}" class="btn btn-sm btn-warning" title="编辑">
                                <i class="bi bi-pencil"></i>
                            </a>
                            <a href="/copy/{{ info.id }}" class="btn btn-sm btn-success" title="复制">
                                <i class="bi bi-clipboard"></i>
                                <!--                                <span class="tooltip-text">复制</span>-->
                            </a>
                            <!--                            <a href="/copy/{{ info.id }}" class="btn btn-sm btn-success copy-tooltip" title="复制">-->
                            <!--                                <i class="bi bi-copy"></i>-->
                            <!--                                <span class="tooltip-text">复制用例</span>-->
                            <!--                            </a>-->
                            <button class="btn btn-sm btn-danger" title="删除"
                                    onclick="confirmDelete({{ info.id }}, '{{ info.case_id }}', '{{ info.version }}', {{ info.operation_sequence }})">
                                <i class="bi bi-trash"></i>
                            </button>
                        </td>
                    </tr>
                    {% endfor %}
                    {% else %}
                    <tr>
                        <td colspan="11" class="text-center py-3">  <!-- 列数增加1 -->
                            <i class="bi bi-info-circle text-muted me-1"></i>
                            没有找到匹配的数据
                        </td>
                    </tr>
                    {% endif %}
                    </tbody>
                </table>
            </div>

            <!-- 分页控件 -->
            {% if pagination.pages > 1 %}
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <li class="page-item {% if not pagination.has_prev %}disabled{% endif %}">
                        <a class="page-link" href="{{ url_for('index', page=pagination.prev_num, system_name=search_system, case_id=search_case_id, module=search_module) }}">
                            <i class="bi bi-chevron-left"></i> 上一页
                        </a>
                    </li>

                    {% for page_num in pagination.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
                    {% if page_num %}
                    <li class="page-item {% if page_num == pagination.page %}active{% endif %}">
                        <a class="page-link" href="{{ url_for('index', page=page_num, system_name=search_system, case_id=search_case_id, module=search_module, version=version) }}">
                            {{ page_num }}
                        </a>
                    </li>
                    {% else %}
                    <li class="page-item disabled">
                        <span class="page-link">...</span>
                    </li>
                    {% endif %}
                    {% endfor %}

                    <li class="page-item {% if not pagination.has_next %}disabled{% endif %}">
                        <a class="page-link" href="{{ url_for('index', page=pagination.next_num, system_name=search_system, case_id=search_case_id, module=search_module, version=version) }}">
                            下一页 <i class="bi bi-chevron-right"></i>
                        </a>
                    </li>
                </ul>
            </nav>
            {% endif %}
        </div>
    </div>
</div>
<!-- 弹窗容器 -->
{% include 'common/alert.html' %}
<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要删除以下用例吗？</p>
                <p><strong>用例编号：</strong><span id="deleteCaseId"></span></p>
                <p><strong>版本号：</strong><span id="deleteVersion"></span></p>
                <p><strong>操作序列：</strong><span id="deleteOperationSequence"></span></p>
                <p class="text-danger"><i class="bi bi-exclamation-triangle me-1"></i> 此操作不可撤销，请谨慎操作！</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <a id="confirmDeleteBtn" href="#" class="btn btn-danger">确认删除</a>
            </div>
        </div>
    </div>
</div>
<!-- 字段说明模态框 -->
{% include 'common/field_modal.html' %}

<script src="/static/js/bootstrap.bundle.min.js"></script>
<script src="/static/js/system_suggest.js"></script>
<script src="/static/js/util.js"></script>
<script>

        document.addEventListener('DOMContentLoaded', function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                setTimeout(function() {
                    // 淡出动画
                    alert.style.opacity = '0';
                    alert.style.transform = 'translateX(100%)';
                    alert.style.transition = 'opacity 0.3s, transform 0.3s';
                    setTimeout(function() {
                        alert.remove();
                    }, 300);
                }, 5000); // 5秒后关闭
            });
        });


        // 系统名称搜索建议功能
        const systemInput = document.getElementById('system_name');
        const systemSuggestions = document.getElementById('systemSuggestions');

        systemInput.addEventListener('focus', function() {
            if (this.value.trim() === '') {
                systemSuggestions.style.display = 'block';
            }
        });

        systemInput.addEventListener('input', function() {
            const value = this.value.toLowerCase().trim();
            const items = systemSuggestions.getElementsByClassName('system-suggestion-item');

            if (value === '') {
                // 显示所有建议
                systemSuggestions.style.display = 'block';
                for (let item of items) {
                    item.style.display = 'block';
                }
            } else {
                // 过滤建议
                let hasVisible = false;
                for (let item of items) {
                    if (item.textContent.toLowerCase().includes(value)) {
                        item.style.display = 'block';
                        hasVisible = true;
                    } else {
                        item.style.display = 'none';
                    }
                }
                systemSuggestions.style.display = hasVisible ? 'block' : 'none';
            }
        });

        // 选择系统名称
        function selectSystem(systemName) {
            systemInput.value = systemName;
            systemSuggestions.style.display = 'none';
        }

        // 点击其他区域关闭建议框
        document.addEventListener('click', function(event) {
            if (!systemInput.contains(event.target) && !systemSuggestions.contains(event.target)) {
                systemSuggestions.style.display = 'none';
            }
        });



// 替换原有的confirmDelete函数
    function confirmDelete(id, caseId, operationSequence, version) {
        // 显示确认模态框
        document.getElementById('deleteVersion').textContent = version;
        document.getElementById('deleteCaseId').textContent = caseId;
        document.getElementById('deleteOperationSequence').textContent = operationSequence;

        // 绑定确认删除按钮事件
        const confirmBtn = document.getElementById('confirmDeleteBtn');
        confirmBtn.onclick = function(e) {
            e.preventDefault(); // 阻止默认跳转

            // 发送AJAX删除请求
            fetch(`/delete/${id}`, {
                method: 'POST', // 使用POST方法更安全
                headers: {
                    'Content-Type': 'application/json',
                    // 添加CSRF令牌（如果启用了Flask-WTF）
                    'X-CSRFToken': getCookie('csrf_token')
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('删除失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // 关闭模态框
                    const deleteModal = bootstrap.Modal.getInstance(document.getElementById('deleteModal'));
                    deleteModal.hide();

                    // 显示成功提示
                    showAlert('删除成功', 'success');

                    // 移除页面上对应的行
                    const row = document.querySelector(`tr[data-id="${id}"]`);
                    if (row) {
                        // 添加删除动画
                        row.style.transition = 'opacity 0.3s, transform 0.3s';
                        row.style.opacity = '0';
                        row.style.transform = 'translateX(-20px)';
                        setTimeout(() => row.remove(), 300);
                    }
                } else {
                    showAlert(`删除失败: ${data.message}`, 'danger');
                }
            })
            .catch(error => {
                showAlert(`删除失败: ${error.message}`, 'danger');
            });
        };

        // 显示模态框
        const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
        deleteModal.show();
    }

    // 显示提示弹窗
    function showAlert(message, type) {
        const alertContainer = document.createElement('div');
        alertContainer.className = 'alert-container';

        const alert = document.createElement('div');
        alert.className = `alert alert-${type}`;
        alert.innerHTML = `
            <i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
            <span>${message}</span>
            <button class="close-btn" onclick="this.parentElement.remove()">&times;</button>
        `;

        alertContainer.appendChild(alert);
        document.body.appendChild(alertContainer);

        // 自动关闭
        setTimeout(() => {
            alert.style.opacity = '0';
            alert.style.transform = 'translateX(100%)';
            alert.style.transition = 'opacity 0.3s, transform 0.3s';
            setTimeout(() => alertContainer.remove(), 300);
        }, 3000);
    }

    // 辅助函数：获取Cookie（用于CSRF验证）
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }


         document.getElementById('exportLink').addEventListener('click', function(e) {
            e.preventDefault();

            // 获取搜索表单中的所有筛选条件
            const systemName = document.getElementById('system_name').value;
            const caseId = document.getElementById('case_id').value;
            const module = document.getElementById('module').value;
            const version = document.getElementById('version').value;

            // 构建导出URL，包含所有筛选条件
            let exportUrl = '/export?';
            const params = [];

            if (systemName) params.push(`system_name=${encodeURIComponent(systemName)}`);
            if (caseId) params.push(`case_id=${encodeURIComponent(caseId)}`);
            if (module) params.push(`module=${encodeURIComponent(module)}`);
            if (version) params.push(`version=${encodeURIComponent(version)}`);

            if (params.length > 0) {
                exportUrl += params.join('&');
            }

            // 跳转到导出页面，携带筛选条件
            window.location.href = exportUrl;
        });
        // 页面加载时检查URL参数，显示提示信息
        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);

            if (urlParams.get('success')) {
                alert('操作成功！');
            }

            if (urlParams.get('error')) {
                alert('操作失败：' + urlParams.get('error'));
            }
        });



</script>
</body>
</html>
